package com.beemans.corekit.integration.polling;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.PowerManager;

import androidx.annotation.Nullable;

import com.beemans.corekit.integration.toolkit.AppUtils;

import java.util.concurrent.atomic.AtomicLong;

public class WakeUtils {
    private static final long CHECK_INTERVAL = 15 * 1000;
    // 上一次检索时间戳
    private static final AtomicLong lastCheckInterval = new AtomicLong(0);

    @Nullable
    private PowerManager.WakeLock wakeLock;

    private static class Holder {
        private static final WakeUtils INSTANCE = new WakeUtils();
    }

    public static WakeUtils getInstance() {
        return Holder.INSTANCE;
    }

    @SuppressLint("WakelockTimeout")
    public void acquire() {
        final long now = System.currentTimeMillis();
        final long last = lastCheckInterval.get();
        if (Math.abs(now - last) < CHECK_INTERVAL) {
            return;
        }

        lastCheckInterval.set(now);

        try {
            if (wakeLock == null) {
                final PowerManager manager = (PowerManager) AppUtils.getApp().getSystemService(Context.POWER_SERVICE);
                wakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WakeUtils.class.getSimpleName() + ":Wakelock Acquire");
            }
            if (wakeLock != null && !wakeLock.isHeld()) {
                wakeLock.acquire();
            }
        } catch (Throwable ignored) {
        }
    }
}
